package o2o.web.actions.pay;


import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ValidateUtil;
import com.jinyouapp.common.tools.jms.model.JMSNotify;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.order.OrderPayMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.jms.config.JMSTypeContent;
import o2o.config.jms.sender.JmsSender;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.common.ResultInfo;
import o2o.dao.PO.order.OrderInfo;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.web.actions.order.OrderMan;
import o2o.web.actions.user.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;


// 此接口不对外  内部用
@Controller
public class SuperAdminOrderController {

    // 订单重新计算分成
    @RequestMapping(method = RequestMethod.POST, value = "/order/pay/recal")
    @ResponseBody
    public String pay_order_wallet(String token, String sysAppKey, String orderNo) {
        // 判断支付方式是否存在
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("无权操作");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单号不能为空");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("订单不存在，请检查订单");
        }

        // 将原有的分成备份删除
        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.OrderPay).append(" set delFlag = 1,updateUser = '").append(user.getUsername()).append("' where delFlag = 0 and orderNo = '" + orderNo + "'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("删除流水失败");
        }

        OrderPayMemory.getInstance().run();
        try {
            JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_RELOAD);
            JmsSender.setTopicSender(notify);
        } catch (Exception e) {
        }

        ShopInfo shopInfo = null;
        if (ValidateUtil.isID(orderInfo.getShopId())) {
            shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
        }

        // 重新计算分成
        ResultInfo resultInfo = OrderPayDistribute.addNormalOrderPayV2(orderNo, orderInfo.getPayType(), null, null, orderInfo.getUsername(), orderInfo, shopInfo);
        if (null == resultInfo) {
            return AjaxResult.errorResult("计算分成失败");
        } else {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        }
        return AjaxResult.successResult();
    }

    // 订单重新计算分成
    @RequestMapping(method = RequestMethod.POST, value = "/order/pay/recal/v2")
    @ResponseBody
    public String pay_order_recal_v2(String token, String sysAppKey, String orderNo) {
        // 判断支付方式是否存在
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("无权操作");
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单号不能为空");
        }

        OrderInfo orderInfo = OrderInfoMemory.getInstance().getOrderInfo(orderNo);
        if (null == orderInfo) {
            return AjaxResult.errorResult("订单不存在，请检查订单");
        }
        ResultInfo resultInfo = dealRecalOrderPay(orderInfo, user.getUsername());
        // 重新计算分成
        if (null == resultInfo) {
            return AjaxResult.errorResult("计算分成失败");
        } else {
            if (!resultInfo.isSuccess()) {
                return AjaxResult.errorResult(resultInfo.getError());
            }
        }
        return AjaxResult.successResult();
    }

    public ResultInfo dealRecalOrderPay(OrderInfo orderInfo, String username) {
        if (OrderMan.isMultipleParentOrder(orderInfo)) {
            HashSet<String> set = OrderInfoMemory.getInstance().listOfParentOrderNo(orderInfo.getOrderNo());
            if (set == null) {
                set = new HashSet<>();
            }
            set.add(orderInfo.getOrderNo());
            Set<String> orderSet = new HashSet<>();
            for (String temp : set) {
                orderSet.add("'" + temp + "'");
            }
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.OrderPay).append(" set delFlag = 1,updateUser = '").append(username).append("' where delFlag = 0 and orderNo in (").append(StringUtils.join(orderSet, ",")).append(")");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo(e.getMessage());
            }

            OrderPayMemory.getInstance().run();
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_RELOAD);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }

            ShopInfo shopInfo = null;
            if (ValidateUtil.isID(orderInfo.getShopId())) {
                shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            }
            ResultInfo resultInfo = OrderPayDistribute.addOrderPayMulti(orderInfo, shopInfo, null, null);
            if (null == resultInfo) {
                return new ResultInfo("重新增加流水失败，请稍后再试。");
            } else {
                if (!resultInfo.isSuccess()) {
                    System.out.println("订单支付成功后增加流水失败 m:" + orderInfo.getOrderNo());
                    return resultInfo;
                }
            }
//            ResultInfo resultInfo = OrderPay.addOrderPay(orderInfo.getOrderNo(), orderInfo.getPayType(), null, null, orderInfo.getUsername(), orderInfo, shopInfo);
            return resultInfo;
        } else {
            // 将原有的分成备份删除
            StringBuffer sb = new StringBuffer();
            sb.append("update ").append(PojoTables.OrderPay).append(" set delFlag = 1,updateUser = '").append(username).append("' where delFlag = 0 and orderNo = '" + orderInfo.getOrderNo() + "'");
            try {
                UserDaoSql.getInstance().executeBySql(sb.toString());
            } catch (SQLException e) {
                e.printStackTrace();
                return new ResultInfo(e.getMessage());
            }

            OrderPayMemory.getInstance().run();
            try {
                JMSNotify notify = JMSNotify.getInstance().setType(JMSTypeContent.ORDER_PAY_RELOAD);
                JmsSender.setTopicSender(notify);
            } catch (Exception e) {
            }

            ShopInfo shopInfo = null;
            if (ValidateUtil.isID(orderInfo.getShopId())) {
                shopInfo = ShopMemory.getInstance().getShopById(orderInfo.getShopId());
            }

            // 重新计算分成
//            ResultInfo resultInfo = OrderPayDistribute.addOrder(orderInfo.getOrderNo(), orderInfo.getPayType(), null, null, orderInfo.getUsername(), orderInfo, shopInfo);
            ResultInfo resultInfo = OrderPay.addOrderPay(orderInfo.getOrderNo(), orderInfo.getPayType(), null, null, orderInfo.getUsername(), orderInfo, shopInfo);
            return resultInfo;
        }

    }

}
